package com.study.rabbitmq.dead;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.study.rabbitmq.utils.RabbitMqUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：黄淼淳
 * @description：死信队列中的普通消费者
 * @date ：2021/12/8 18:21
 */
public class Comsume {
    private static final String NORMAL_EXCHANGE = "normal_exchange";
    private static final String DEAD_EXCHANGE = "dead_exchange";
    public static final String NORMAL_QUEUE = "normal_queue";
    public static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws IOException {
        Channel channel = RabbitMqUtil.getChannel();
        //定义为直接交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        //定义死信交换机
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        //声明一个死信队列
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, "lisi");

        Map<String, Object> arguments = new HashMap<>();
        //设置过期时间为10s
        //arguments.put("x-message-ttl",10000);
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", "lisi");
        //设置正常队列的限制长度
        //arguments.put("x-max-length",6);

        channel.queueDeclare(NORMAL_QUEUE, false, false, false, arguments);
        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, "zhangsan");

        System.out.println("Comsume01等待接收消息。。。。。。");
        //绑定交换机和队列

        DeliverCallback deliverCallback = (comsumeTag, message) -> {
            String msg = new String(message.getBody(),StandardCharsets.UTF_8);
            if (msg.equals("info5"))
                channel.basicReject(message.getEnvelope().getDeliveryTag(), false);
            else {
                System.out.println("Comsume01接收到的消息：" + new String(message.getBody(), StandardCharsets.UTF_8));
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            }
        };
        CancelCallback cancelCallback = (comsumeTag) -> {
        };
        //开启手动应答
        channel.basicConsume(NORMAL_QUEUE,false, deliverCallback, cancelCallback);

    }
}

